import './Login.scss'
import { Card, Form, Input } from 'antd'
import logo from '@/assets/logo.png'
import { useState } from 'react';
import { fetchLogin } from '@/store/userSlice';
import { useAppDispatch } from '@/store/store';
import { useNavigate } from 'react-router-dom';
import { LoginFormData } from '@/apis/userApi';
import FormSubmitButton from '@/components/FormSubmitButton/FormSubmitButton';

// 登录表单组件
const Login = () => {
    const appDispatch = useAppDispatch();
    const navigate = useNavigate();

    // 表单提交事件
    const [loading, setLoading] = useState<boolean>(false);
    const login = (formData: LoginFormData) => {
        setLoading(true);
        // 使用store发布登录thunk函数
        appDispatch(fetchLogin(formData)).then(() => {
            setLoading(false);
            // 跳转到首页
            navigate('/');
        }).catch(() => {
            setLoading(false);
        });
    };

    return (
        <div className="login">
            <Card className="login-container">
                <img className="login-logo" src={logo} alt="" />
                {/* 登录表单 */}
                <Form validateTrigger={['onBlur']} onFinish={login}>
                    <Form.Item
                        name='mobile'
                        rules={[
                            { required: true, message: '请输入手机号！' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号！' }
                        ]}
                        validateFirst={true}
                        validateDebounce={500}
                        hasFeedback>
                        <Input size="large" placeholder="请输入手机号" />
                    </Form.Item>
                    <Form.Item
                        name='code'
                        rules={[
                            { required: true, message: '请输入验证码！' }
                        ]}
                        validateDebounce={500}
                        hasFeedback>
                        <Input size="large" placeholder="请输入验证码" maxLength={6} />
                    </Form.Item>
                    <Form.Item>
                        <FormSubmitButton loading={loading} text='登录' block={true} />
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Login;